<?php
/*
 * @Author       : ZengHao
 * @Date         : 2024-01-08 19:11:51
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-01-09 20:34:56
 * @FilePath     : /inc/core/user.php
 * @Description  : 
 * Copyright 2024 www.exehub.com, All Rights Reserved. 
 * 2024-01-08 19:11:51
 */

//刷新头像缓存
add_action('user_save_custom_avatar', function ($user_id) {
    ECache::delete('user_avatar'.$user_id);
    el_get_data_avatar($user_id);
}, 10);

function el_get_data_avatar($user_id = '', $size = '60', $alt = '')
{
    $args = array(
        'size'   => $size,
        'height' => $size,
        'width'  => $size,
        'alt'    => $alt,
    );
    $cache = ECache::get('user_avatar'.$user_id);
    if (false === $cache) {
        $avatar = el_get_avatar(null, $user_id, $args);
        ECache::set('user_avatar'.$user_id,$avatar);
    } else {
        $avatar = $cache;
    }
    // 是否懒加载
    // if (el_is_lazy('lazy_avatar')) {
    //     $avatar = str_replace(' src=', ' src="' . el_default_avatar() . '" data-src=', $avatar);
    //     $avatar = str_replace(' class="', ' class="lazyload ', $avatar);
    // }
    return $avatar;
}


add_filter('pre_get_avatar', 'el_get_avatar', 10, 3);
function el_get_avatar($avatar, $id_or_email, $args)
{
    $user_id = el_get_user_id($id_or_email);

    $custom_avatar = $user_id ? get_user_meta($user_id, 'custom_avatar', true) : '';
    $alt           = $user_id ? get_the_author_meta('nickname', $user_id) . '的头像' . el_get_delimiter_blog_name() : '头像';

    $avatar = $custom_avatar ? $custom_avatar : el_default_avatar();

    //优化百度头像地址
    $avatar = str_replace('tb.himg.baidu.com', 'himg.bdimg.com', $avatar);
    $avatar = preg_replace("/^(https:|http:)/", "", $avatar);

    $args['size'] = esc_attr($args['size']);
    return '<img alt="' . esc_attr($alt) . '" src="' . esc_url($avatar) . '" class="lazyload avatar' . ($args['size'] ? ' avatar-' . $args['size'] : '') . ' avatar-id-' . $user_id . '"' . ($args['size'] ? ' height="' . $args['size'] . '" width="' . $args['size'] . '"' : '') . '>';
}

//获取用户id
function el_get_user_id($id_or_email)
{
    $user_id = '';
    if (is_numeric($id_or_email)) {
        $user_id = (int) $id_or_email;
    } elseif (is_string($id_or_email) && ($user = get_user_by('email', $id_or_email))) {
        $user_id = $user->ID;
    } elseif (is_object($id_or_email) && !empty($id_or_email->user_id)) {
        $user_id = (int) $id_or_email->user_id;
    }

    return $user_id;
}

//用户默认头像
function el_default_avatar()
{
    return _opz('avatar_default_img') ?: EL_ASSETS . 'img/def_avatar.png';
}